# 存储日志
import json
from datetime import datetime

from app import redis_client,redis_ready,set_redis_error


def add_log_event(message, detail,level="error"):
    try:
        if redis_ready:
            log_data = {
                "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "message": message,
                "detail": detail,
                "level": level,
            }
            redis_client.rpush("system_logs", json.dumps(log_data))
            # 限制列表长度，避免无限增长
            redis_client.ltrim("system_logs", -1000, -1)  # 保留最近1000条记录
    except Exception as e:
        set_redis_error()

# 获取日志
def get_logs():
    try:
        if redis_ready:
            logs = redis_client.lrange("system_logs", 0, -1)
            return [json.loads(log) for log in logs]
        return []
    except Exception as e:
        set_redis_error()
        return []